<?php
namespace Helpers;

use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\user\XhsysUser;
use Phalcon\Di;

class Hrm
{

    /**
     * 根据用户id获取部门id
     *
     * @param null $userId
     * @param bool|false $getArray
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20171017
     * modify by ck 20171019    可获取数组
     */
    public static function getDepId($userId = null, $getArray = false)
    {
        $userId or $userId = Main::getLoginUserInfo('userId');
        if (!$userId) {
            throw new \Exception('缺少用户id');
        }
        $staff = XhhrmStaff::findFirst([
            'columns' => 'sDepIds',
            'conditions' => 'iUserId = :userId: AND bDelete = 0 and iStaffStatus = 1',
            'bind' => ['userId' => $userId]
        ]);
        if (!$staff) {
            throw new \Exception('找不到该员工信息');
        }
        $depIds = explode(',', trim($staff->sDepIds, ','));
        if (!$depIds) {
            throw new \Exception('该员工未分配部门');
        }
        return $getArray ? $depIds : end($depIds);
    }

    /**
     * 根据用户id获取部门下用户id数组
     *
     * @param null $userId
     * @return array
     * @throws \Exception
     *
     * create by ck 20171017
     */
    public static function getDepUserIdByUser($userId = null)
    {
        $depId = self::getDepId($userId);
        $userList = XhhrmStaff::find([
            'columns' => 'iUserId',
            'conditions' => 'iUserId > 0 AND bDelete = 0 AND sDepIds LIKE :depId: and iStaffStatus = 1',
            'bind' => ['depId' => "%,{$depId},%"]
        ])->toArray();
        if (!$userList) {
            throw new \Exception('未获取到部门下人员列表');
        }
        return array_column($userList, 'iUserId');
    }

    /**
     * 获取 部门+名字 格式的StaffEnum (staffId)
     *
     * @return array
     *
     * create by dale  20181112
     */
    public static function getFlowStaffWithDepName()
    {
        $staffArr = XhhrmStaff::find([
            'columns'    => 'iStaffId,sStaffName,sDepIds,iUserId',
            'conditions' => 'bDelete= 0 and iStaffStatus = 1 and iUserId is not null',
        ])->toArray();
        if (!$staffArr) {
            return [];
        }
        $depArr = XhhrmDepart::getDepEnum();
        foreach ($staffArr as &$staff) {
            $dep = array_filter(explode(',', $staff['sDepIds']));
            if ($dep) {
                $firstDep = end($dep);
                $depName = Tool::getValue($depArr, $firstDep, '');
                if ($depName) {
                    $staff['sStaffName'] .= "({$depName})";
                }
            }
        }
        unset($staff);
        return array_column($staffArr, 'sStaffName', 'iStaffId');
    }

    /**
     * 获取 部门+名字 格式的StaffEnum (userId)
     *
     * @return array
     *
     * create by dale  20181214
     */
    public static function getUserWithDepName()
    {
        $staffArr = XhhrmStaff::find([
            'columns'    => 'iStaffId,sStaffName,sDepIds,iUserId',
            'conditions' => 'bDelete= 0 and iStaffStatus = 1 and iUserId is not null',
        ])->toArray();
        if (!$staffArr) {
            return [];
        }
        $depArr = XhhrmDepart::getDepEnum();
        foreach ($staffArr as &$staff) {
            $dep = array_filter(explode(',', $staff['sDepIds']));
            if ($dep) {
                $firstDep = end($dep);
                $depName = Tool::getValue($depArr, $firstDep, '');
                if ($depName) {
                    $staff['sStaffName'] .= "({$depName})";
                }
            }
        }
        unset($staff);
        return array_column($staffArr, 'sStaffName', 'iUserId');
    }


    /**
     * 获取部门信息
     *
     * @param null $userId
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20171019
     */
    public static function getDepInfoByUser($userId = null)
    {
        $depIds = self::getDepId($userId, true);
        $depInfo = XhhrmDepart::find([
            'columns' => 'sTag AS tag, iDepId AS id, sDepName AS name',
            'conditions' => 'bDelete = 0 AND iDepId IN ({idArr:array})',
            'bind' => ['idArr' => $depIds]
        ])->toArray();
        if (!$depInfo) {
            throw new \Exception('部门信息获取失败');
        }
        return $depInfo;
    }

    /**
     * 根据标签及深度返回该部门结构
     *
     * @param null $tag 标签
     * @param int $depth 深度
     * @param bool $withKey 是否显示主键
     * @return array|bool
     *
     * created by dale 20171124
     */
    public static function getDepArray($tag = null, $depth = 0, $withKey = false)
    {
        if ($tag) {//tag
            $tag = strtoupper($tag);
            $obj = XhhrmDepart::findFirst([
                'conditions' => 'bDelete =0 AND sTag = :sTag:',
                'bind' => ['sTag' => $tag]
            ]);
            if (!$obj) {
                return false;
            } else {
                $data = self::recursionForDep($obj->iDepId, $depth, $withKey);
            }
        } else {//没有tag
            $data = self::recursionForDep(0, $depth, $withKey);
        }
        return $data;
    }

    /**
     * 根据id获取其负责部门下的所有人id,可以指定，默认当前登录用户
     *
     * @param null $iUserId
     * @return array|bool
     *
     * created by dale 2017124
     * modify by dale 20181119  去除在职判断
     */
    public static function getInChargeUserIds($iUserId = null)
    {
        if ($iUserId == null) {
            $iUserId = Main::getLoginUserInfo('userId');
            $logName = Main::getLoginUserInfo('logonName');
        } else {
            $user = XhsysUser::findFirst($iUserId);
            if (!$user) {
                return false;
            } else {
                $logName = $user->sLogonName;
            }
        }
        if ($logName == 'admin') {
            return true;
        } else {
            $staff = XhhrmStaff::findFirst([
                'columns' => 'sChargeDeps',
                'conditions' => 'iUserId = :iUserId: and iStaffStatus = 1',
                'bind' => ['iUserId' => $iUserId],
            ]);
            if ($staff->sChargeDeps == null) {
                return false;
            } else {
                $deps = array_values(array_unique(array_filter(explode(',', $staff->sChargeDeps))));
                $conditions = 'bDelete=0 ';
                $deps = implode(",%' OR  sDepIds like '%,", $deps);
                $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
                $powerIds = XhhrmStaff::find([
                    'columns' => 'iUserId',
                    'conditions' => $conditions,
                ]);
                return $powerIds->toArray();
            }
        }

    }


    /**
     *
     *
     * @param $parentId --父id
     * @param int $depth --需求深度
     * @param bool $withKey --是否包含主键
     * @param int $current --当前深度
     * @return array
     * created by dale 2017/11/24
     */
    private static function recursionForDep($parentId, $depth = 0, $withKey = false, $current = 0)
    {
        $parameters = array(
            'columns' => 'iDepId,sDepName,sTag',
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' => $parentId, 'bDelete' => 0),
        );
        $array = XhhrmDepart::find($parameters)->toArray();
        if ($array == []) {
            return $array;
        }
        $newArray = [];
        foreach ($array as $key => $value) {
//            if($withKey){
            $newArray[$key]['id'] = $value['iDepId'];
//            }
            $newArray[$key]['text'] = $value['sDepName'];
            $newArray[$key]['tag'] = $value['sTag'];
            if ($depth == 0) {
                $newArray[$key]['child'] = self::recursionForDep($value['iDepId'], $depth, $withKey, $current + 1);
            } else if ($depth != 0 && $depth != $current + 1) { //需求深度不为0 且 需求深度 和当前深度加一不等
                $newArray[$key]['child'] = self::recursionForDep($value['iDepId'], $depth, $withKey, $current + 1);
            } else {
                $newArray[$key]['child'] = [];
            }
            if ($newArray[$key]['child'] == []) {
                unset($newArray[$key]['child']);
            }
        }
        return $newArray;
    }

    /**
     * 根据标签获取部门下的人
     *
     * @param string $tag
     * @return XhhrmStaff|XhhrmStaff[]|array|bool
     *
     * create by dale 20171211
     */
    public static function getDepStaffByTag($tag = 'all')
    {
        $tag = strtoupper($tag);//转大写
        if (!$tag || $tag == 'ALL') {
            $staff = XhhrmStaff::find([
                'columns' => 'iUserId,sStaffName',
                'conditions' => 'bDelete = 0 and iStaffStatus = 1',
            ]);
        } else {
            $dep = XhhrmDepart::findFirst([
                'columns' => 'iDepId',
                'conditions' => 'sTag = :sTag: AND bDelete = 0 ',
                'bind' => ['sTag' => $tag]
            ]);
            if (!$dep) {
                return false;
            }
            $staff = XhhrmStaff::find([
                'columns' => 'iUserId,sStaffName',
                'conditions' => 'bDelete = 0 AND  sDepIds like :key: and iStaffStatus = 1 and iUserId is not null',
                'bind' => ['key' => '%,' . $dep->iDepId . ',%']
            ]);
        }
        $staff = array_column($staff->toArray(), 'sStaffName', 'iUserId');
        return $staff;
    }


    /**
     * 根据部门id数组获取部门下用户id
     *
     * @param array $depIds
     * @param $merge
     * @return array
     * @throws \Exception
     *
     *  create by dale 20180416
     *  modify by dale 20181119  移除在职判断
     */
    public static function getUserByDepId($depIds = [], $merge = false)
    {
        is_string($depIds) and $depIds = [$depIds];
        $conditionArr = [
            'columns' => 'sDepIds,iUserId',
            'conditions' => 'bDelete = 0 ',
        ];
        $arr = [];
        foreach ($depIds as $depId) {
            $arr[] = " sDepIds like '%,{$depId},%' ";

        }
        $conditionArr['conditions'] .= ' and (' . implode(' OR ', $arr) . ')';
        $deps = XhhrmStaff::find($conditionArr)->toArray();
        if ($merge) {
            return array_values(array_filter(array_column($deps, 'iUserId')));
        }
        if (count($deps) <= 0) {
            return [];
//            throw new \Exception('未找到部门标签');
        }
        $depUser = [];
        foreach ($depIds as $index => $depId) {
            $depUser[$depId] = [];
            foreach ($deps as $dep) {
                if (strpos($dep['sDepIds'], ",{$depId},") !== false && $dep['iUserId']) {
                    $depUser[$depId][] = $dep['iUserId'];
                }
            }
        }

        return $depUser;
    }

    /**
     * 根据部门id获取部门下的职工userId
     *
     * @param $depIds
     *
     * @return array
     *
     * create by dale  20181112
     */
    public static function getDepUserIdByDepId($depIds)
    {
        if (is_string($depIds)) {
            $depIds = explode(',', $depIds);
        }
        if (!$depIds) {
            return [];
        }
        $conditionArr = [
            'columns' => 'sDepIds,iUserId',
            'conditions' => 'bDelete = 0 and iUserId is not null ',
        ];
        $arr = [];
        foreach ($depIds as $depId) {
            $arr[] = " sDepIds like '%,{$depId},%' ";
        }
        if ($arr) {
            $conditionArr['conditions'] .= 'and (' . implode(' OR ', $arr) . ')';
        }
        $depUserIds = XhhrmStaff::find($conditionArr)->toArray();
        if (!$depUserIds) {
            return [];
        }
        return array_values(array_unique(array_filter(array_column($depUserIds, 'iUserId'))));
    }

    /**
     * 根据部门tag获取部门下的职工userId
     *
     * @param $depTagArr
     *
     * @return array
     *
     * create by dale  20181112
     */
    public static function getDepUserIdByDepTag($depTagArr)
    {
        if (is_string($depTagArr)) {
            $depTagArr = explode(',', $depTagArr);
        }
        if (!$depTagArr) {
            return [];
        }
        $depIds = array_values(self::getDepIdTagRelation('depTag', $depTagArr));
        return self::getDepUserIdByDepId($depIds);
    }


    /**
     * 获取depId和depTag的关系
     *
     * @param $arrType
     * @param $arr
     *
     * @return array
     *
     * create by dale  20181112
     */
    public static function getDepIdTagRelation($arrType, $arr = [])
    {
        if (!$arrType) {
            return [];
        }
        if ($arrType == 'depId') {
            if (!$arr) {
                return [];
            }
            $depArr = XhhrmDepart::find([
                'columns'    => 'iDepId,sTag',
                'conditions' => 'bDelete = 0 and iDepId in ({ids:array})',
                'bind'       => ['ids' => $arr]
            ])->toArray();
            if (!$depArr) {
                return [];
            }
            return array_column($depArr, 'sTag','iDepId');
        } else if ($arrType == 'depTag') {
            if (!$arr) {
                return [];
            }
            $depArr = XhhrmDepart::find([
                'columns'    => 'iDepId,sTag',
                'conditions' => 'bDelete = 0 and sTag in ({ids:array})',
                'bind'       => ['ids' => $arr]
            ])->toArray();
            if (!$depArr) {
                return [];
            }
            return array_column($depArr, 'iDepId','sTag');
        } else if ($arrType == 'all') {
            $depArr = XhhrmDepart::find([
                'columns'    => 'iDepId,sTag',
                'conditions' => 'bDelete = 0 ',
            ])->toArray();
            if (!$depArr) {
                return [];
            }
            return array_column($depArr, 'sTag','iDepId');
        } else {
            return [];
        }
    }


    public static function getDepStaff()
    {
        $cacheKey = 'depStaffList';
        if (Cache::exists($cacheKey)) {
            return Cache::get($cacheKey);
        }
        $depInfo = XhhrmDepart::find([
            'columns' => 'iDepId AS depId,sDepName AS depName',
            'conditions' => 'bDelete = 0 AND iParentId = 0'
        ])->toArray();
        foreach ($depInfo as $index => $dep) {
            $staffInfo = XhhrmStaff::find([
                'columns' => 'iStaffId AS staffId,iUserId AS userId,sStaffName AS staffName',
                'conditions' => 'bDelete = 0 AND sDepIds LIKE :depId: and iStaffStatus = 1',
                'bind' => ['depId' => "%,{$dep['depId']},%"]
            ])->toArray();
            $depInfo[$index]['staffList'] = $staffInfo;
        }
        Cache::save($cacheKey, $depInfo);
        return $depInfo;
    }

    public static function getFlowDepStaff()
    {
        $data = [];
        foreach (self::getDepStaff() as $index => $dep) {
            if (empty($dep['staffList'])) {
                continue;
            }
            $data[$index] = ['id' => $dep['depId'], 'text' => $dep['depName']];
            foreach ($dep['staffList'] as $staff) {
                if (!$staff['userId']) {
                    continue;
                }
                $data[$index]['children'][] = ['id' => $staff['userId'], 'text' => $staff['staffName']];
            }
        }
        return array_values($data);
    }

    /**
     * 获取部门负责人userId
     *
     * @param null $userId
     * @param bool $all 为true 获取用户所有负责人userId
     *
     * @return array|bool|mixed|string
     *
     * create by dale  20181030
     */
    public static function getLeader($userId = null, $all = false)
    {
        if (!$userId) {
            $userId = Main::getLoginUserInfo('userId');
        }
        $staff = XhhrmStaff::findFirst([
            'columns' => 'sDepIds',
            'conditions' => 'bDelete= 0 and iUserId = :iUserId: and iStaffStatus = 1 ',
            'bind' => ['iUserId' => $userId],
        ]);
        if (!$staff) {
            return false;
        }
        if (!$all) { // 只获取上一级不部门负责人
            $depId = current(array_values(array_filter(explode(',', $staff->sDepIds))));
            if (!$depId) {
                return false;
            }
            $chargerStaff = Di::getDefault()->get('db')->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff 
              where CONCAT(',',sChargeDeps,',') like '%,{$depId},%' ");
            if (!$chargerStaff) {
                return false;
            }
            return Tool::getValue($chargerStaff, 'iUserId', false);
        } else {
            $depIdArr = array_values(array_filter(explode(',', $staff->sDepIds)));
            if (!$depIdArr) {
                return false;
            }
            $sql = "SELECT iUserId, sChargeDeps FROM XHHrm_Staff ";
            $conditions = [];
            foreach ($depIdArr as $depId) {
                $conditions[] = "CONCAT(',',sChargeDeps,',') like '%,{$depId},%' ";
            }
            $sql .= " where " . implode(' or ', $conditions);
            $chargerStaffArr = Di::getDefault()->get('db')->fetchAll($sql);
            if (!$chargerStaffArr) {
                return false;
            }
            $userIdArr = array_values(array_filter(array_unique(array_column($chargerStaffArr, 'iUserId'))));
            return $userIdArr;
        }
    }

    /**
     * 获取在职员工
     *
     * @return array
     *
     * create by dale  20181113
     */
    public static function getInHireStaff()
    {
        $staffArr = XhhrmStaff::find([
            'columns'    => 'iStaffId,sStaffName',
            'conditions' => 'bDelete= 0 and iStaffStatus = 1'
        ])->toArray();
        return array_column($staffArr, 'sStaffName', 'iStaffId');
    }

    /**
     * 根据userId批量替换为职工姓名
     *
     * @param $obj
     * @param $fields
     * @param $isArray
     *
     * create by dale  20181102
     */
    public static function runStaffNameByUserId(&$obj, $fields, $isArray = false)
    {
        $userIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        if ($isArray) {
            foreach ($fields as $idField => $nameField) {
                $userIdArr = array_merge($userIdArr, array_column($obj, $idField));
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach ($obj as $index => $objOne) {
                foreach ($fields as $idField => $nameField) {
                    if (!isset($userNameArr[$objOne[$idField]])) continue;
                    $obj[$index][$nameField] = $userNameArr[$objOne[$idField]];
                }
            }
        } else {
            foreach ($fields as $idField => $nameField) {
                $userIdArr = array_merge($userIdArr, $obj[$idField]);
            }
            $userNameArr = XhhrmStaff::getStaffNameById($userIdArr);
            foreach ($fields as $idField => $nameField) {
                if (!isset($userNameArr[$obj[$idField]])) continue;
                $obj[$nameField] = $userNameArr[$obj[$idField]];
            }
        }
    }

    /**
     * 根据关键字搜索职工id和姓名
     *
     * @param $key
     * @param bool $withName
     *
     * @return array
     *
     * create by qgz 20181102
     */
    public static function searchStaffUser($key, $withName = false)
    {
        $users = XhhrmStaff::find([
            'columns' => 'iUserId, sStaffName',
            'conditions' => "bDelete = 0 AND sStaffName LIKE '%{$key}%' and iStaffStatus = 1"
        ])->toArray();
        $machIds = array_column($users, 'sStaffName', 'iUserId');
        return $withName ? $machIds : array_keys($machIds);
    }

    /**
     * 处理部门名称
     *
     * @param $obj
     * @param $fields
     * @return bool
     *
     * create by ck 20181108
     */
    public static function runDepName(&$obj, $fields)
    {
        if (!$obj || !$fields) {
            return false;
        }
        $depIdArr = [];
        is_string($fields) and $fields = [$fields => $fields];
        foreach ($fields as $idField => $nameField) {
            $depIds = array_column($obj, $idField);
            $depIdArr = array_merge($depIdArr, $depIds);
        }
        $depNames = XhhrmDepart::find([
            'columns' => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND iDepId IN ({depIds:array}) ',
            'bind' => ['depIds' => $depIdArr]
        ])->toArray();
        $depNames = array_column($depNames, 'sDepName', 'iDepId');
        foreach ($obj as $index => &$objOne) {
            foreach ($fields as $idField => $nameField) {
                $objOne[$nameField] = Tool::getValue($depNames, $objOne[$idField]);
            }
        }
        return true;
    }

    /**
     * 根据userId获取职工信息
     *
     * @param array $userIdArr
     * @param bool $allDep  false
     *
     * @return array
     *
     * create by dale  20181119
     */
    public static function getStaffInfo($userIdArr = [], $allDep = false)
    {
        if (!$userIdArr) {
            return [];
        }
        $staffArr = XhhrmStaff::find([
            'columns'    => 'sStaffName as staffName,iUserId as userId,sSelfPhone as phoneNumber,sDepIds as depId',
            'conditions' => 'bDelete = 0 and iUserId in ({ids:array})',
            'bind'       => ['ids' => $userIdArr]
        ])->toArray();
        foreach ($staffArr as &$staff) {
            $staff['depName'] =
                $allDep ? XhhrmDepart::getDepName($staff['depId']) : XhhrmDepart::getFirstDepName($staff['depId']);
        }
        unset($staff);
        $staffArr = array_column($staffArr, null, 'userId');
        return $staffArr;
    }

    /**
     * 获取在职的员工信息
     *
     * @return array
     *
     * create by dale  20181227
     */
    public static function getInHireStaffInfo()
    {
        $staffArr = XhhrmStaff::find([
            'columns'    => 'sStaffName as staffName,iUserId as userId,sSelfPhone as phoneNumber,sDepIds as depId',
            'conditions' => 'bDelete = 0 and iStaffStatus = 1 and iUserId is not null',
        ])->toArray();
        $staffArr = array_column($staffArr, null, 'userId');
        return $staffArr;
    }

    /**
     * 获取当前登陆的用户信息
     *
     * @return int
     * @throws \Exception
     *
     * create by dale  20190124
     */
    public static function getLoginStaffId()
    {
        if (!User::isAdmin()) {
            $userId = Main::getLoginUserInfo('userId');
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'iStaffId',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind'       => ['iUserId' => $userId]
            ]);
            if (!$staff) {
                throw new \Exception('没有职工信息');
            }
            $staffId = $staff->iStaffId;
        } else {
            $config     = Main::getConfigByName('hrm');
            $adminPhone = Tool::getValue($config, 'adminStaffPhone');
            if (!$adminPhone) {
                throw new \Exception('没有hrm:adminStaffPhone配置项');
            }
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'iStaffId',
                'conditions' => 'bDelete = 0 and sSelfPhone = :sSelfPhone:',
                'bind'       => ['sSelfPhone' => $adminPhone]
            ]);
            if (!$staff) {
                throw new \Exception('没有职工信息');
            }
            $staffId = $staff->iStaffId;
        }
        return $staffId;
    }

}